//获取权限方法
var userInfo = getAuthority();
var powerlist = JSON.parse(userInfo).permissions;
/*自定义函数判断权限*/
template.defaults.imports.hasPower = function(data){
    if(powerlist.includes(data)){
        return true;
    }
    return false;
};

layui.use(['admin','element', 'layer','form','notice'], function() {
    var admin = layui.admin;
    var element = layui.element;
    var layer = layui.layer;
    var form = layui.form;
    var notice = layui.notice;

    var curMeta= admin.getLayerData();  // 获取列表页面传递的数据; 保存综合对象信息及id
    var dataTemp={
        id: undefined,
        version: undefined
    };
    var filter={
        period: "",
        region: undefined,
        curRegion: {
            rcid: "",
            regioncode: ""
        },
        version: ""
    };
    var matid= ""; //保存综合对象id
    var rcid= ""; //区划代码
    var showPversion=false; //是否显示多版本
    var setting={//树设置
        regionSetting:{//区划树设置
            async: {
                enable: true,
                url: '',
                type: "get",
            },
            edit: {
                enable: true,
                showRemoveBtn: false,
                showRenameBtn: false,
                drag: {
                    isCopy: true,
                    isMove: false,
                    prev: false,
                    next: false,
                    inner: false
                }
            },
            data: {
                key: {
                    children: "sub"
                },
                simpleData: {
                    enable: true
                }
            },
            callback: {
                onClick: regionTreeOnClick,
                onExpand: onExpandRegionTree
            },
            view: {
                showIcon: true,
                showLine: true
            }
        },
    }

    if(userInfo){
        var access_token = localStorage.getExpire("access_token");
        var token_type = localStorage.getExpire("token_type");
        Authorization = token_type+" "+access_token;

        getQueryDataPower();
        init();
    }

    form.on('select(regionSet)', function(data){
        queryRegionTree(data.value);
    });

    //监听提交
    form.on('submit(queryData)', function(data){
        queryData(data.field);
        return false;
    });

    $("#regionInput").click(function() {
        $("#groupRegion").show();
    });

    form.on('select(period)', function(data){
        filter.period= data.value;
        getDataVersion();
        return false;
    });


    function getQueryDataPower() {
        var str = template("queryData-tmpl",{});
        document.getElementById("queryData-tmpl-box").innerHTML = str;
    }

    function init(){
        getRegionVersion();
    }

    //查询区划配置版本
    function getRegionVersion() {
        let req = {
            current:1,
            flag:0,
            size:pageSize_noPage
        }
        axios.get(regionUrl.catalog.catalogList,{
            params:req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var arr = response.data.data;
                    var str = template("region-tree-tmpl",arr);
                    document.getElementById("region-tree-box").innerHTML = str;
                    form.render('select')
                    if(arr.total>0){
                        rcid = arr.records[0].id;
                        queryRegionTree(rcid);

                    }
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }

    //查询行政区划树
    function queryRegionTree(value) {
        rcid = value;
        //清空报告期和数据版本
        filter.period=undefined;
        filter.version = undefined;
        var periodstr = template("period-select-tmpl",{});
        document.getElementById("period-select-box").innerHTML = periodstr;

        var pversionstr = template("pversion-select-tmpl",{});
        document.getElementById("pversion-select-box").innerHTML = pversionstr;

        form.render('select');

        $("#regionInput input").val("");

        lazyLoadRegionTree();
    }

    //查询下方区划树的下级区划值（懒加载）
    function onExpandRegionTree(event, treeId, treeNode) {
        if(treeNode.sub.length<1){
            var req = {
                rcId: rcid,
                regionCode: treeNode.code,
                regionCodeType: 1
            };
            getRegion(req,function (datas) {
                const treeObj = $.fn.zTree.getZTreeObj("groupRegion");
                treeObj.addNodes(treeNode, datas);
            });
        }

    }

    //查询某一对象某一报告期下原始数据
    function queryData(data) {
        if (!data.period) {
            notice.msg('请先选择报告期！', {icon: 3});
            return;
        }

        var str = data.period;
        var period = str.split(",");

        const args = {
            maid: curMeta.id,
            rcid: rcid,
            regioncode: filter.curRegion.regioncode,
            year: Number(period[0]),
            month: Number(period[1]),
            pversion: filter.version.pversion
        };
        clearTable();

        axios.get(macroUrl.data.queryData,{
            params: args,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var arr = response.data.data;
                    if(arr!=null){
                        var datas = strAllReplaceLine(arr);
                        dataTemp = {
                            id: datas.id,
                            version: datas.version
                        };
                        $("#left_div1").html(datas.cross_table);
                        $("#right_divx").html(datas.column_table);
                        $("#left_div2").html(datas.row_table);
                        $("#right_div2").html(datas.data_table);
                        setTableStyle();
                        tableSize();
                        $("#data_table tr td input").attr("placeholder", "");
                    }

                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });

    }

    //设置表格滑动样式
    function setTableStyle() {
        var right_div2 = document.getElementById("right_div2");
        right_div2.onscroll = function() {
            var right_div2_top = scrollTop;
            var right_div2_left = scrollLeft;
            document.getElementById("left_div2").scrollTop = right_div2_top;
            document.getElementById("right_div1").scrollLeft = right_div2_left;
        };
        //设置右边div宽度
        tableSize();
        $("#right_div").width(document.documentElement.clientWidth - 130);
        setInterval(function() {
            $("#right_div").width(document.documentElement.clientWidth - 130);
        }, 0);
    }
    
    function tableSize() {
        const height = document.documentElement.clientHeight - 43 * 4 - 130;
        tableWidth = $("#left_div2").width() + $("#right_div2").width() + 2;
        tableHeight = height - $("#left_div1").height();
        $(".tableWidth").css("width",tableWidth)
    }

    //清空表
    function clearTable() {
        $("#left_div1").html("");
        $("#right_divx").html("");
        $("#left_div2").html("");
        $("#right_div2").html("");
    }

    //区划树
    function lazyLoadRegionTree(curRegionCode) {

        //查询区划放在下方显示的树
        var code = "";
        if (curRegionCode) {
            code = curRegionCode;
        }
        var req = {
            rcId: rcid,
            regionCode: code,
            regionCodeType: 1
        };
        getRegion(req,function (datas) {
            $.fn.zTree.init($("#groupRegion"), setting.regionSetting, datas);
        })
    }

    //查询区划数据
    function getRegion(req,callback) {
        axios.get(regionUrl.info.queryRegion,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var arr = response.data.data;
                    var datas = [];
                    for(var i = 0; i < arr.length; i++ ){
                        datas[i] = strAllReplaceLine(arr[i]);
                    }
                    if (datas.length > 0) {
                        for (const row of datas) {
                            row.cat_id = row.id;
                            row.isParent = true;
                            row.attribute = {
                                isRegionCode: true,
                                groupCode: row.code,
                                groupName: row.name,
                                isPeriod: false,
                                period: "",
                                ig_type: "group",
                                path: "",
                                pathName: "",
                                idencomparsion: ""
                            };
                            row.sub = []; //存放子节点
                            row.drag = true;
                        }
                    }
                    callback(datas);
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }

    //区划树点击
    function regionTreeOnClick(event, treeId, treeNode){
        $("#regionInput input").val(treeNode.name);
        filter.curRegion.regioncode  = treeNode.code;
        $("#groupRegion").hide();
        getTablePeriod();
    }

    //查询表报告期
    function getTablePeriod() {
        let req = {
            maid:curMeta.id,
            rcid:rcid,
            regioncode:filter.curRegion.regioncode
        }
        axios.get(macroUrl.macro_period.dataPeriod,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var arr = response.data;
                    if(arr.data.length>0){
                        var str = template("period-select-tmpl",arr);
                        document.getElementById("period-select-box").innerHTML = str;
                        form.render('select');
                        filter.period=arr.data[0].year+','+arr.data[0].month;
                        getDataVersion();
                    }else{
                        //清空报告期和数据版本
                        filter.period=undefined;
                        filter.version = undefined;
                        var periodstr = template("period-select-tmpl",{});
                        document.getElementById("period-select-box").innerHTML = periodstr;

                        var pversionstr = template("pversion-select-tmpl",{});
                        document.getElementById("pversion-select-box").innerHTML = pversionstr;

                        form.render('select');
                    }
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }
    
    //查询数据版本
    function getDataVersion() {
        var str = filter.period;
        var period = str.split(",");

        let req = {
            maid:curMeta.id,
            rcid:rcid,
            regioncode:filter.curRegion.regioncode,
            year:period[0],
            month:period[1]
        }

        axios.get(macroUrl.macro_period.dataVersion,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var arr = response.data;
                    if(arr.data.length>0){
                        var str = template("pversion-select-tmpl",arr);
                        document.getElementById("pversion-select-box").innerHTML = str;
                        form.render('select');
                        filter.version = arr.data[0];
                    }
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }

})